package csci5828.tasks.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;

import csci5828.tasks.TaskResult;
import csci5828.tasks.TaskResults;

public class TaskResultsImpl<T> implements TaskResults<T> {
	
	private List<T> availableResults;
	private BlockingQueue<TaskResult<T>> queue;
	private TaskResult<T> elem;
	private boolean pending;
	private int timeoutMillis;

	public TaskResultsImpl(List<TaskResult<T>> availableResults, BlockingQueue<TaskResult<T>> queue, boolean pending) {
		this.availableResults = new ArrayList<T>();
		for (TaskResult<T> taskResult: availableResults) {
			this.availableResults.add(taskResult.getResult());
		}
		this.queue = queue;
		this.elem = null;
		this.pending = pending;
		this.timeoutMillis = 30000;
	}
	
	public boolean isPending() {
		return pending;
	}
	
	@Override
	public boolean next() throws InterruptedException {
		if (isPending()) {
    		this.elem = queue.poll(timeoutMillis, TimeUnit.MILLISECONDS);
    		if (this.elem == null)
    			throw new InterruptedException("timeout exceeded");
    		if (this.elem.getResult() == null)
    			this.pending = false;
    		return this.elem.getResult() != null;
		}
		return false;
	}
	
	@Override
	public List<T> getAvailableResults() {
		return this.availableResults;
	}

	@Override
	public T get() {
		return this.elem.getResult();
	}

}
